
var express = require('express');
var router = express.Router();
const jwt=require('jsonwebtoken')
const dayjs=require('dayjs');
const AccountModel = require('../../modules/account');
/* GET home page. */
router.get('/account', function(req, res, next) {
  const token = req.get('token')
  console.log(token)
  if(!token){
    res.json({
      code:'2003',
      msg:'token缺失！'
    })
  }else{
    jwt.verify(token,'atguigu',(err,data)=>{
     if(err){
      res.json({
        code:'2004',
        msg:'token错误！'
      })
     }else{
      AccountModel.find().sort({date:-1}).then(response=>{
    res.json({
        code:'2000',
        msg:'读取成功',
        data:response
      })
  })
      
        
     }
  })
}
});
router.post('/account/add', function(req, res, next) {
    const newdate=dayjs(req.body.date).format()
   const data={...req.body,date:newdate}
   AccountModel.create({
    ...data
   }).then(resonse=>{
    res.json({
        code:'0000',
        msg:'添加信息成功！',
        data:data
    })
   }).catch(err=>{
    res.json({
        msg:err.message,
        data:null
    })
   })
 
});
router.delete('/account/:id', function(req, res, next) {
  let {id}=req.params
  AccountModel.delete({_id:id}).then(response=>{
   res.json({
    code:200,
    msg:'删除成功',
    data:response
   })
  },error=>{
    res.json({
      code:404,
      msg:error.message,
      data:null
     })
  })
});
router.get('/account/:id', function(req, res, next) {
  let {id}=req.params
  AccountModel.findOne({id:id}).then(response=>{
   res.json({
    code:200,
    msg:'查找成功',
    data:response
   })
  },error=>{
    res.json({
      code:404,
      msg:error.message,
      data:null
     })
  })
});
router.patch('/account/:id',(req,res)=>{
    const {id}=req.params
    const data=req.body
    AccountModel.updateOne({_id:id},data).then(response=>{
      res.json({
        code:200,
        msg:'更新成功',
        data:response
       })
      },error=>{
        res.json({
          code:404,
          msg:error.message,
          data:null
         })
      })
})

module.exports = router;
